package com.cnblogs.leizia.crm.workbench.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cnblogs.leizia.crm.commen.RequestUri;
import com.cnblogs.leizia.crm.commen.Result;
import com.cnblogs.leizia.crm.settings.domain.User;
import com.cnblogs.leizia.crm.settings.service.UserService;
import com.cnblogs.leizia.crm.settings.service.impl.UserServiceImpl;
import com.cnblogs.leizia.crm.utils.DateTimeUtil;
import com.cnblogs.leizia.crm.utils.PrintJson;
import com.cnblogs.leizia.crm.utils.ServiceFactory;
import com.cnblogs.leizia.crm.utils.UUIDUtil;
import com.cnblogs.leizia.crm.workbench.dao.TranDao;
import com.cnblogs.leizia.crm.workbench.domain.*;
import com.cnblogs.leizia.crm.workbench.service.*;
import com.cnblogs.leizia.crm.workbench.service.impl.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 交易模块控制器
 *
 * @author leizi
 * @create 2021-04-05 0:02
 */
public class TranController extends HttpServlet {

    TranService tranService = (TranService) ServiceFactory.getService(new TranServiceImpl());
    UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());
    ActivityService activityService = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
    CustomerService customerService = (CustomerService) ServiceFactory.getService(new CustomerServiceImpl());
    ContactsService contactsService = (ContactsService) ServiceFactory.getService(new ContactsServiceImpl());

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();

        if (RequestUri.TRAN_ADD.getUriPath().equals(path)) {
            tranCreate(req, resp);
        }
        if (RequestUri.TRAN_GET_CUSTOMER_NAME.getUriPath().equals(path)) {
            getCustomerName(req, resp);
        }
        if (RequestUri.TRAN_SAVE.getUriPath().equals(path)) {
            saveTran(req, resp);
        }
        if (RequestUri.TRAN_SEARCH_ACTIVITYLIST.getUriPath().equals(path)) {
            searchActivitylist(req, resp);
        }
        if (RequestUri.TRAN_SEARCH_CONTACTSLIST.getUriPath().equals(path)) {
            searchContactsList(req, resp);
        }
        if (RequestUri.TRAN_DETAIL.getUriPath().equals(path)) {
            detail(req, resp);
        }
        if (RequestUri.TRAN_TRAN_HISTORY_LIST.getUriPath().equals(path)) {
            tranHistoryList(req, resp);
        }
        if (RequestUri.TRAN_TRAN_CHANGE_STAGE.getUriPath().equals(path)) {
            tranChangeStage(req, resp);
        }

    }

    public Result tranChangeStage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String stage = request.getParameter("stage");
        String money = request.getParameter("money");
        String expectedDate = request.getParameter("expectedDate");
        Tran tran = new Tran();
        tran.setId(id);
        tran.setStage(stage);
        tran.setMoney(money);
        tran.setExpectedDate(expectedDate);
        // 修改时间
        tran.setEditTime(DateTimeUtil.getSysTime());
        User user = (User) request.getSession().getAttribute("user");
        // 修改人
        tran.setEditBy(user.getName());
        String stage2 = (String) request.getServletContext().getAttribute("stage2");
        Map<String, String> map = JSONObject.parseObject(stage2, Map.class);
        String possibility = map.get(stage);
        // 修改交易信息
        Tran tranChangeStage = tranService.tranChangeStage(tran, possibility);

        PrintJson.printJsonObj(response,Result.successToDataResult(tranChangeStage));

        return null;
    }

    /**
     * 根据交易id获取交易历史
     *
     * @param request
     * @param response
     * @return
     */
    private Result tranHistoryList(HttpServletRequest request, HttpServletResponse response) {
        String tranId = request.getParameter("tranId");

        // 根据获取交易id获取交易历史
        List<TranHistory> tranHistoryList = tranService.tranHistoryList(tranId);
        // 转换'可能性'
        String stage2 = (String) request.getServletContext().getAttribute("stage2");
        Map<String, String> map = JSON.parseObject(stage2, Map.class);

        for (TranHistory tranHistory : tranHistoryList) {
            String stage = tranHistory.getStage();
            tranHistory.setPossibility(map.get(stage));
        }
        PrintJson.printJsonObj(response, Result.successToDataResult(tranHistoryList));

        return null;
    }

    /**
     * 交易详情
     *
     * @param request
     * @param response
     * @return
     */
    private Result detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tranId = request.getParameter("tranId");

        // 根据交易id获取交易详情信息
        Tran tran = tranService.detail(tranId);

        String stage = tran.getStage();

        // 转换'可能性'
        String stage2 = (String) request.getServletContext().getAttribute("stage2");
        Map<String, String> map = JSON.parseObject(stage2, Map.class);
        String possibility = map.get(stage);

        request.setAttribute("tran", tran);
        request.setAttribute("possibility", possibility);

        request.getRequestDispatcher("/workbench/transaction/detail.jsp").forward(request, response);

        return null;
    }

    /**
     * 根据名称查找联系人
     *
     * @param request
     * @param response
     * @return
     */
    private Result searchContactsList(HttpServletRequest request, HttpServletResponse response) {

        String name = request.getParameter("name");
        List<Contacts> contactsList = contactsService.getContactsList(name);
        PrintJson.printJsonObj(response, Result.successToDataResult(contactsList));

        return null;
    }

    /**
     * 根据名称查找市场活动
     *
     * @param request
     * @param response
     * @return
     */
    private Result searchActivitylist(HttpServletRequest request, HttpServletResponse response) {

        String name = request.getParameter("name");
        List<Activity> clueActivityList = activityService.getClueActivityList(name, null);

        PrintJson.printJsonObj(response, Result.successToDataResult(clueActivityList));

        return null;
    }

    /**
     * 保存交易
     *
     * @param request
     * @param response
     * @return
     */
    private Result saveTran(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String owner = request.getParameter("owner");
        String money = request.getParameter("money");
        String name = request.getParameter("name");
        String expectedClosingDate = request.getParameter("expectedClosingDate");
        String accountName = request.getParameter("accountName");
        String stage = request.getParameter("stage");
        String type = request.getParameter("type");
        String source = request.getParameter("source");
        String activityId = request.getParameter("activityId");
        String contactsId = request.getParameter("contactsId");
        String describe = request.getParameter("describe");
        String summary = request.getParameter("summary");
        String nextContactTime = request.getParameter("nextContactTime");

        // 校验客户是否存在
        Customer customer = customerService.getCustomer(accountName);
        if (Objects.isNull(customer)) {
            PrintJson.printJsonObj(response, Result.errorResult("客户不存在!"));
        }

        Tran tran = new Tran();
        tran.setId(UUIDUtil.getUUID());
        tran.setOwner(owner);
        tran.setMoney(money);
        tran.setName(name);
        tran.setExpectedDate(expectedClosingDate);
        tran.setCustomerId(customer.getId());
        tran.setStage(stage);
        tran.setType(type);
        tran.setSource(source);
        tran.setActivityId(activityId);
        tran.setContactsId(contactsId);
        tran.setContactSummary(summary);
        tran.setNextContactTime(nextContactTime);
        User user = (User) request.getSession().getAttribute("user");
        tran.setCreateBy(user.getName());
        tran.setCreateTime(DateTimeUtil.getSysTime());
        tran.setDescription(describe);

        tranService.saveTran(tran);

        response.sendRedirect(request.getContextPath() + "/workbench/transaction/index.jsp");

        return null;
    }

    /**
     * 获取客户名称
     *
     * @param req
     * @param resp
     * @return
     */
    private Result getCustomerName(HttpServletRequest req, HttpServletResponse resp) {
        String name = req.getParameter("name");
        List<String> customerNameList = customerService.getCustomerName(name);

        PrintJson.printJsonObj(resp, Result.successToDataResult(customerNameList));

        return null;
    }

    /**
     * 创建交易
     *
     * @return
     */
    private Result tranCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户名列表
        List<User> userList = userService.getUserList();
        request.setAttribute("userList", userList);
        // 转发到创建页
        request.getRequestDispatcher("/workbench/transaction/save.jsp").forward(request, response);

        return null;
    }
}
